<template>
  <div
    :id="id"
    v-loading="loading"
    :element-loading-text="loadingTitle"
    element-loading-spinner="el-icon-loading"
    :style="{ width: width, height: height }"
  >
  </div>
</template>

<script>
import {getUUID} from "@/utils/index";

export default {
  name: "YiEchart",
  props: {
    id: {
      type: String,
      default: () => getUUID()
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: "370px"
    },
    isClick: { // 是否增加点击事件
      type: Boolean,
      default: false
    },
    realTime: { // 是否需要轮询数据
      type: Boolean,
      default: false
    },
    realTimeSecond: { // 轮询秒数
      type: Number,
      default: 120
    }
  },
  data() {
    return {
      echartsBox: null, // Echart实例对象
      loading: true, // loading
      timing: null, // 轮询定时器
      loadingTitle: "数据加载中..."
    }
  },
  methods: {
    getEchartData() { // 组件加载成功后回调函数
      this.$emit('getEchartData', {id: this.id});
    },
    init(data) { // 初始化 echarts
      this.disposeEchart();
      // 1.echart实例对象生成
      this.echartsBox = this.$echarts.init(document.getElementById(this.id));
      let option = data;
      this.echartsBox.setOption(option);
      // 2.初始化去掉加载框
      this.loading = false;
      // 3.自适应
      window.removeEventListener('resize', this.resizeEcharts);
      window.addEventListener("resize", this.resizeEcharts);
      // 4.增加点击事件
      if (this.isClick) {
        this.echartsBox.on('click', (params) => {
          this.$emit('echartsClick', params);
        })
      }
      // 5.是否需要轮询数据
      if (this.realTime) this.dataPolling();
    },
    dataPolling() { // 数据轮询
      this.timing = setTimeout(() => {
        clearTimeout(this.timing);
        this.timing = null;
        this.getEchartData();
      }, 1000 * this.realTimeSecond);
    },
    resizeEcharts() { // echart 响应式
      if (this.echartsBox) this.echartsBox.resize();
    },
    refreshEcharts(option, notMerge = true) { // echarts合并新的参数和数据，然后刷新图表，不清空销毁画布
      if (option && this.echartsBox) this.echartsBox.setOption(option, notMerge)
    },
    getEchartsImg() { // 生成图片
      let imgSrc = this.echartsBox.getDataURL();
      return imgSrc;
    },
    clearEchart() { // 清空画布
      if (this.echartsBox) this.echartsBox.clear();
    },
    disposeEchart() { // 销毁 Echart 实例对象
      if (this.echartsBox) {
        this.$echarts.dispose(this.echartsBox);
        this.echartsBox = null;
      }
    }
  },
  mounted() {
    this.getEchartData();
  },
  beforeDestroy() {
    this.disposeEchart();
    if (this.timing) clearTimeout(this.timing);
    this.timing = null;
    window.removeEventListener('resize', this.resizeEcharts);
  }
}
</script>
